package org.uba.userStat.service;

import org.springframework.stereotype.Service;
import org.uba.common.AppClient;
import org.uba.common.ChartData;
import org.uba.common.TimeGranularity;
import org.uba.common.TimeSlot;
import org.uba.userStat.repo.NewUserStatRepo;
import sun.swing.BakedArrayList;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class NewUserStatService {
    @Resource
    private NewUserStatRepo nusRepo;
    public ChartData generateNewUserStat(TimeSlot tlt, TimeGranularity tgr, AppClient ac) {
        Map<String,Long> map = new LinkedHashMap<>();

        List<Date> dates = tlt.getSplitTimesByGra(tgr);
        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
        dates.forEach(date->{
            map.put(sdf.format(date),0L);
        });

        List<Map<String,Object>> list ;
        String appKey = getAppKey();
        if(ac == null){
            list =  nusRepo.statNewuser(appKey,tlt.getStartTime(),tlt.getEndTime(),tgr.getKey(),null,null);
        }else {
            list =  nusRepo.statNewuser(appKey,tlt.getStartTime(),tlt.getEndTime(),tgr.getKey(),ac.getType(),ac.getVersion());
        }
        list.forEach(m->{
            Timestamp ts = (Timestamp) m.get("date_trunc");
            long count = (Long) m.get("count");
            map.put(sdf.format(ts),count);
        });

        ChartData cd = new ChartData();
        cd.setX(map.keySet());
        cd.setS( map.values());
        return cd;
    }

    public String getAppKey(){
        return nusRepo.getAppKey();
    }
}
